import IRenderer from "../../base/ECSR/IRenderer"
import Entity from "../../base/ECSR/Entity";
import MovePathComponent from "../components/MovePathComponent";

export default class MovePathRenderer extends IRenderer
{
    currPathIndex = -1;
    moveTween:cc.Tween = null;

    // 子类需要实现的方法
    OnRender(entity:Entity, dt:number):void 
    {
        let movePathCom = entity.GetComponent("MovePathComponent") as MovePathComponent;
        if(movePathCom == null) return;

        cc.log("MovePathRenderer|node.position=" + this.node.getPosition().toString());


        // 有变化
        if(movePathCom.currPathStartIndex != this.currPathIndex)
        {
            this.currPathIndex = movePathCom.currPathStartIndex;

            if(this.moveTween)
            {
                this.moveTween.stop();
            }

            this.node.setPosition(movePathCom.path[movePathCom.currPathStartIndex]);
            
            cc.log("MovePathRenderer|currPathStartIndex=" + movePathCom.currPathStartIndex + ", pos=" + movePathCom.path[movePathCom.currPathStartIndex].toString());

            let targetPos = null;
            // 达到终点
            if(movePathCom.currPathStartIndex >=  movePathCom.path.length - 1)
            {
                targetPos = movePathCom.targetPos;
            }
            else
            {
                targetPos = movePathCom.path[movePathCom.currPathStartIndex + 1];
            }

            let node = this.node;
            let moveTime = movePathCom.time * 0.033;
            cc.log("MovePathRenderer|moveTime=" + moveTime + ", targetPos=" + targetPos.toString());

            this.moveTween = cc.tween(this.node)
                .to(moveTime, {position: cc.v3(targetPos.x, targetPos.y, 0)})
                .call(()=>{
                    node.setPosition(targetPos);
                });

            this.moveTween.start();
        }

    }
}